import Cocoa
import Foundation

// MARK: - Core Logic Helper Functions (核心逻辑辅助函数)

// 辅助函数：将 snake_case 转换为 camelCase (蛇形命名转换为驼峰命名)
func snakeToCamel(_ s: String) -> String {
    let pattern = "([_-][a-z])" // 匹配下划线或连字符后面跟着小写字母的模式
    guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
        return s // 如果正则表达式无效，返回原始字符串
    }

    var result = s // 用于构建结果的可变字符串
    let nsRange = NSRange(s.startIndex..<s.endIndex, in: s) // 原始字符串的 NSRange

    // 获取所有匹配项
    let matches = regex.matches(in: s, options: [], range: nsRange)

    // 从后向前遍历匹配项，以避免在替换时影响后续匹配项的范围
    for match in matches.reversed() {
        // 获取匹配到的完整字符串（例如 "_name", "-id"）
        guard let rangeToReplace = Range(match.range, in: result) else { continue }
        let matchedSubstring = String(result[rangeToReplace])

        // 对匹配到的子字符串进行转换：转换为大写，并移除下划线或连字符
        let transformed = matchedSubstring.uppercased()
                                         .replacingOccurrences(of: "-", with: "")
                                         .replacingOccurrences(of: "_", with: "")
        
        // 在结果字符串中替换匹配到的范围
        result.replaceSubrange(rangeToReplace, with: transformed)
    }
    return result
}

// 辅助函数：将字符串的首字母大写
func capitalizeFirstLetter(_ string: String) -> String {
    guard !string.isEmpty else { return "" }
    return string.prefix(1).uppercased() + string.dropFirst()
}

// 定义一个结构体来存储生成的模型代码
struct GeneratedModels {
    var swiftCode: String = ""
    var objcHeader: String = ""
    var objcImplementation: String = ""
    var flutterCode: String = ""
}

// 主模型生成函数
// 参数:
// - jsonDataString: 包含 JSON 数据的字符串
// - rootModelName: 根模型的名称
// - classNamePrefix: 类名前缀 (新增参数)
// - targetLanguages: 一个集合，包含需要生成的语言（例如：[.swift, .objc, .flutter]）
// - swiftFramework: Swift 框架选项 (例如：.codable, .handyJSON, .swiftyJSON)
// - objcFramework: Objective-C 框架选项 (例如：.system, .mjExtension, .yyModel)
// - flutterFramework: Flutter 框架选项 (例如：.system, .jsonSerializable)
// 返回: GeneratedModels 结构体，包含生成的各种语言代码
func generateModels(
    jsonDataString: String,
    rootModelName: String,
    classNamePrefix: String, // 恢复 classNamePrefix 参数
    targetLanguages: Set<String>, // "swift", "objc", "flutter"
    swiftFramework: String = "Codable", // "Codable", "HandyJSON", "SwiftyJSON"
    objcFramework: String = "System", // "System", "MJExtension", "YYModel"
    flutterFramework: String = "System" // "System", "JsonSerializable"
) throws -> GeneratedModels {
    var generated = GeneratedModels()

    guard let jsonData = jsonDataString.data(using: .utf8) else {
        throw NSError(domain: "JSONError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无效的 JSON 数据。"])
    }

    let parsedData: Any
    do {
        parsedData = try JSONSerialization.jsonObject(with: jsonData, options: [])
    } catch {
        throw NSError(domain: "JSONError", code: 2, userInfo: [NSLocalizedDescriptionKey: "JSON 解析失败：\(error.localizedDescription)"])
    }

    var rootDataForModel: [String: Any] = [:]

    // 检查根 JSON 是否包含 'code', 'msg', 'data' 结构
    if let dict = parsedData as? [String: Any],
       let data = dict["data"] as? [String: Any] {
        rootDataForModel = data
    } else if let dict = parsedData as? [String: Any] {
        // 如果根就是字典，直接使用
        rootDataForModel = dict
    } else {
        throw NSError(domain: "JSONError", code: 3, userInfo: [NSLocalizedDescriptionKey: "JSON 根结构不是预期的字典或包含 'data' 键的字典。"])
    }

    var allGeneratedSwiftModels: [String: String] = [:]
    var allGeneratedObjcHeaders: [String: String] = [:]
    var allGeneratedObjcImplementations: [String: String] = [:]
    var allGeneratedFlutterModels: [String: String] = [:]

    var processedModelNames = Set<String>()

    // 用于 Swift 和 Flutter 的全局导入
    var swiftGlobalImports = Set<String>(["import Foundation"])
    var flutterGlobalImports = Set<String>()
    var flutterPartDeclarations = Set<String>()


    // 递归函数：处理 JSON 并构建模型
    func processObject(_ obj: [String: Any], _ currentModelName: String) {
        // 如果模型已处理，则直接返回，避免重复处理
        guard !processedModelNames.contains(currentModelName) else { return }
        processedModelNames.insert(currentModelName)

        var objcProperties: [String] = []
        var objcSynthesize: [String] = []
        var objcInitAssignments: [String] = []
        var objcCustomPropertyMappers: [String] = [] // 用于 MJExtension/YYModel 的属性映射
        var objcContainerPropertyGenericClasses: [String] = [] // 用于 MJExtension/YYModel 的容器属性泛型类映射

        var swiftProperties: [String] = []
        var swiftProtocolConformance = ": Codable" // 默认遵循 Codable
        var swiftClassOrStructDeclaration = "struct" // 默认声明为 struct
        var swiftInitializerBody = "" // 自定义初始化器的内容
        var swiftCodingKeys: [String] = []

        var flutterProperties: [String] = []
        var flutterConstructorParams: [String] = []
        var flutterFromJsonLines: [String] = []
        var flutterToJsonLines: [String] = []

        // 根据 Swift 框架调整全局导入和模型声明
        if swiftFramework == "HandyJSON" {
            swiftGlobalImports.insert("import HandyJSON")
            // swiftGlobalImports.insert("import UIKit") // HandyJSON 示例通常包含 UIKit，但对于核心逻辑不是必需的
            swiftProtocolConformance = ": HandyJSON"
            swiftClassOrStructDeclaration = "class" // HandyJSON 通常使用 class
            swiftInitializerBody = "\n    required init() {}\n"
        } else if swiftFramework == "SwiftyJSON" {
            swiftGlobalImports.insert("import SwiftyJSON")
            swiftProtocolConformance = "" // SwiftyJSON 模型不需要遵循特定协议进行映射
            swiftClassOrStructDeclaration = "class" // SwiftyJSON 解析时通常使用 class
            swiftInitializerBody = "\n    init(_ json: JSON) {\n"
        }

        for (key, value) in obj {
            let camelKey = snakeToCamel(key) // 将 snake_case 转换为 camelKey

            // --- Swift 属性推断 ---
            var swiftPropertyType: String
            var swiftPropertySuffix = "" // 用于 HandyJSON 的默认值或 !
            var isCodableOptional = false // 用于 Codable 的 '?'

            // Swift 类型推断逻辑
            if value is String {
                // 尝试将字符串解析为 Int，然后 Double，然后 Bool，最后默认为 String
                if let intVal = Int(value as! String) {
                    if intVal > Int32.max || intVal < Int32.min {
                        swiftPropertyType = "Int64"
                    } else {
                        swiftPropertyType = "Int"
                    }
                    if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = 0" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].intValue\n" }
                } else if let doubleVal = Double(value as! String) {
                    swiftPropertyType = "Double"
                    if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = 0.0" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].doubleValue\n" }
                } else if (value as! String).lowercased() == "true" || (value as! String).lowercased() == "false" {
                    swiftPropertyType = "Bool"
                    if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = false" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].boolValue\n" }
                } else {
                    swiftPropertyType = "String"
                    if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = \"\"" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].stringValue\n" }
                }
            } else if value is Int {
                if (value as! Int) > Int32.max || (value as! Int) < Int32.min {
                    swiftPropertyType = "Int64"
                } else {
                    swiftPropertyType = "Int"
                }
                if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = 0" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].intValue\n" }
            } else if value is Double {
                swiftPropertyType = "Double"
                if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = 0.0" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].doubleValue\n" }
            } else if value is Bool {
                swiftPropertyType = "Bool"
                if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = false" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].boolValue\n" }
            } else if let array = value as? [Any] {
                var arrayElementType = "Any"
                if let firstElement = array.first {
                    if let nestedObj = firstElement as? [String: Any] {
                        let nestedModelName = "\(currentModelName)\(capitalizeFirstLetter(camelKey))"
                        processObject(nestedObj, nestedModelName) // 递归处理嵌套对象
                        arrayElementType = nestedModelName
                    } else if firstElement is String { arrayElementType = "String" }
                    else if firstElement is Int { arrayElementType = "Int" }
                    else if firstElement is Double { arrayElementType = "Double" }
                    else if firstElement is Bool { arrayElementType = "Bool" }
                }
                swiftPropertyType = "[\(arrayElementType)]"
                if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = []" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" {
                    if arrayElementType.contains("Model") { // 对象数组
                        swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].arrayValue.compactMap { \(arrayElementType)(json: $0) }\n"
                    } else { // 原始类型数组
                        swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].arrayObject as? [\(arrayElementType)] ?? []\n"
                    }
                }
            } else if let nestedObj = value as? [String: Any] {
                let nestedModelName = "\(currentModelName)\(capitalizeFirstLetter(camelKey))"
                processObject(nestedObj, nestedModelName) // 递归处理嵌套对象
                swiftPropertyType = nestedModelName
                if swiftFramework == "HandyJSON" { swiftPropertySuffix = "!" } else if swiftFramework == "Codable" { isCodableOptional = true } else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = \(nestedModelName)(json: json[\"\(key)\"])\n" }
            } else if value is NSNull {
                // Swift 中通常用 Optional 来表示 null
                swiftPropertyType = "Any" // 更通用的可选类型
                isCodableOptional = true
                if swiftFramework == "HandyJSON" { swiftPropertySuffix = " = nil" }
                else if swiftFramework == "SwiftyJSON" { swiftInitializerBody += "        self.\(camelKey) = json[\"\(key)\"].object as? Any\n" }
            } else {
                swiftPropertyType = "Any" // 默认 Any 类型
                isCodableOptional = true
            }

            // 添加属性声明行
            var propDeclaration = "    var \(camelKey): \(swiftPropertyType)"
            if swiftFramework == "Codable" {
                propDeclaration += isCodableOptional ? "?" : ""
            } else if swiftFramework == "HandyJSON" {
                propDeclaration += swiftPropertySuffix
            } else if swiftFramework == "SwiftyJSON" {
                propDeclaration += "?"
            }
            swiftProperties.append(propDeclaration)

            // 如果原始键与驼峰命名键不同，则为 Codable 添加 CodingKey
            if swiftFramework == "Codable" && camelKey != key {
                swiftCodingKeys.append("        case \(camelKey) = \"\(key)\"")
            }

            // --- Objective-C 属性推断和映射 ---
            var objcType: String
            var finalObjcPropertyName = camelKey
            var objcPropertyAttributes = "(nonatomic, strong)"

            let problematicObjcKeywords = Set([
                "id", "new", "description", "class", "hash", "init", "alloc", "copy", "mutableCopy",
                "retain", "release", "autorelease", "dealloc", "self", "super",
                "private", "protected", "public", "readwrite", "readonly", "assign",
                "strong", "weak", "copy", "atomic", "nonatomic"
            ])

            if key != camelKey || problematicObjcKeywords.contains(camelKey) || problematicObjcKeywords.contains(key) {
                if key == "id" {
                    finalObjcPropertyName = "objId"
                    if objcFramework == "MJExtension" || objcFramework == "YYModel" {
                        objcCustomPropertyMappers.append("        @\"\(finalObjcPropertyName)\" : @\"\(key)\",")
                    }
                } else if problematicObjcKeywords.contains(camelKey) {
                    finalObjcPropertyName = "_\(camelKey)"
                    if objcFramework == "MJExtension" || objcFramework == "YYModel" {
                        objcCustomPropertyMappers.append("        @\"\(finalObjcPropertyName)\" : @\"\(key)\",")
                    }
                } else if key != camelKey {
                    if objcFramework == "MJExtension" || objcFramework == "YYModel" {
                        objcCustomPropertyMappers.append("        @\"\(camelKey)\" : @\"\(key)\",")
                    }
                }
            }

            // Objective-C 类型推断细化
            if value is String {
                if let intVal = Int(value as! String) {
                    objcType = "NSInteger"
                    objcPropertyAttributes = "(nonatomic, assign)"
                } else if let doubleVal = Double(value as! String) {
                    objcType = "CGFloat"
                    objcPropertyAttributes = "(nonatomic, assign)"
                } else if (value as! String).lowercased() == "true" || (value as! String).lowercased() == "false" {
                    objcType = "BOOL"
                    objcPropertyAttributes = "(nonatomic, assign)"
                } else {
                    objcType = "NSString *"
                    objcPropertyAttributes = "(nonatomic, copy)"
                }
            } else if value is Int {
                objcType = "NSInteger"
                objcPropertyAttributes = "(nonatomic, assign)"
            } else if value is Double {
                objcType = "CGFloat"
                objcPropertyAttributes = "(nonatomic, assign)"
            } else if value is Bool {
                objcType = "BOOL"
                objcPropertyAttributes = "(nonatomic, assign)"
            } else if let array = value as? [Any] {
                var inferredArrayElementType = "id"
                if let firstElement = array.first {
                    if let nestedObj = firstElement as? [String: Any] {
                        let nestedModelNameOC = "\(currentModelName)\(capitalizeFirstLetter(camelKey))"
                        processObject(nestedObj, nestedModelNameOC)
                        // 修复: 字符串插值中的括号平衡问题
                        objcType = "NSArray<\(nestedModelNameOC) *> *"
                        if objcFramework == "MJExtension" {
                            objcContainerPropertyGenericClasses.append("        @\"\(finalObjcPropertyName)\" : [\(nestedModelNameOC) class],")
                        } else if objcFramework == "YYModel" {
                            // 修复: finalModelName 不存在，应为 finalObjcPropertyName
                            objcContainerPropertyGenericClasses.append("        @\"\(finalObjcPropertyName)\" : [\(nestedModelNameOC) class],")
                        }
                    } else if firstElement is String { inferredArrayElementType = "NSString *" }
                    else if firstElement is Int { inferredArrayElementType = "NSNumber *" }
                    else if firstElement is Double { inferredArrayElementType = "NSNumber *" }
                    else if firstElement is Bool { inferredArrayElementType = "NSNumber *" }
                    objcType = "NSArray<\(inferredArrayElementType)> *"
                } else {
                    objcType = "NSArray *"
                }
                objcPropertyAttributes = "(nonatomic, copy)"
            } else if let nestedObj = value as? [String: Any] {
                let nestedModelNameOC = "\(currentModelName)\(capitalizeFirstLetter(camelKey))"
                processObject(nestedObj, nestedModelNameOC)
                // 修复: 字符串插值中的括号平衡问题
                objcType = "\(nestedModelNameOC) *"
                objcPropertyAttributes = "(nonatomic, strong)"
            } else if value is NSNull {
                objcType = "id"
                objcPropertyAttributes = "(nonatomic, strong)"
            } else {
                objcType = "id"
                objcPropertyAttributes = "(nonatomic, strong)"
            }

            objcProperties.append("@property \(objcPropertyAttributes) \(objcType)\(objcType.hasSuffix("*") ? "" : " ")\(finalObjcPropertyName);")

            if objcFramework == "System" {
                objcSynthesize.append("@synthesize \(finalObjcPropertyName) = _\(finalObjcPropertyName);")
                
                var objCInitAssignment: String = "" // 修复: 在所有路径开始前声明并初始化

                let className = objcType.replacingOccurrences(of: " *", with: "")

                // 修复: 修正逻辑以确保 objCInitAssignment 总是被赋值
                if objcType.contains("*") && !objcType.contains("NSString *") && !objcType.contains("NSArray") && !objcType.contains("id") {
                    // 这是自定义对象类型（例如嵌套模型）
                    objCInitAssignment = """
                        if ([dictionary[@"\(key)"] isKindOfClass:[NSDictionary class]]) {
                            _\(finalObjcPropertyName) = [[NSClassFromString(@\"\(className)\") alloc] initWithDictionary:dictionary[@"\(key)"]];
                        }
"""
                } else if objcType == "NSInteger" || objcType == "BOOL" || objcType == "CGFloat" {
                    var castMethod = ""
                    if objcType == "NSInteger" { castMethod = "integerValue" }
                    else if objcType == "BOOL" { castMethod = "boolValue" }
                    else if objcType == "CGFloat" { castMethod = "doubleValue" }
                    objCInitAssignment = "        _\(finalObjcPropertyName) = [dictionary[@\"\(key)\"] \(castMethod)];"
                } else {
                    // 默认情况：NSString *, NSArray *, id, 或未处理的类型
                    objCInitAssignment = "        _\(finalObjcPropertyName) = dictionary[@\"\(key)\"];"
                }
                objcInitAssignments.append(objCInitAssignment)
            }

            // --- Flutter 属性声明和映射 ---
            var flutterPropertyType = "dynamic"
            var flutterFromJsonCast = ""
            var flutterToJsonMapping = "this.\(camelKey)"

            if value is String {
                flutterPropertyType = "String"
                flutterFromJsonCast = "json['\(key)'] as String?"
            } else if value is Int {
                flutterPropertyType = "int"
                flutterFromJsonCast = "json['\(key)'] as int?"
            } else if value is Double {
                flutterPropertyType = "double"
                flutterFromJsonCast = "json['\(key)'] as double?"
            } else if value is Bool {
                flutterPropertyType = "bool"
                flutterFromJsonCast = "json['\(key)'] as bool?"
            } else if let array = value as? [Any] {
                var arrayElementType = "dynamic"
                if let firstElement = array.first {
                    if let nestedObj = firstElement as? [String: Any] {
                        let nestedModelNameFlutter = "\(currentModelName)\(capitalizeFirstLetter(camelKey))"
                        processObject(nestedObj, nestedModelNameFlutter)
                        arrayElementType = nestedModelNameFlutter
                    } else if firstElement is String { arrayElementType = "String" }
                    else if firstElement is Int { arrayElementType = "int" }
                    else if firstElement is Double { arrayElementType = "double" }
                    else if firstElement is Bool { arrayElementType = "bool" }
                }
                flutterPropertyType = "List<\(arrayElementType)>"
                if flutterFramework == "System" {
                    if arrayElementType.contains(currentModelName) {
                        flutterFromJsonCast = "(json['\(key)'] as List<dynamic>?)?.map((e) => \(arrayElementType).fromJson(e as Map<String, dynamic>)).toList()"
                        flutterToJsonMapping = "this.\(camelKey)?.map((e) => e.toJson()).toList()"
                    } else {
                        flutterFromJsonCast = "(json['\(key)'] as List<dynamic>?)?.cast<\(arrayElementType)>().toList()"
                    }
                }
            } else if let nestedObj = value as? [String: Any] {
                let nestedModelNameFlutter = "\(currentModelName)\(capitalizeFirstLetter(camelKey))"
                processObject(nestedObj, nestedModelNameFlutter)
                flutterPropertyType = nestedModelNameFlutter
                if flutterFramework == "System" {
                    flutterFromJsonCast = "json['\(key)'] == nil ? nil : \(nestedModelNameFlutter).fromJson(json['\(key)'] as Map<String, dynamic>)"
                    flutterToJsonMapping = "this.\(camelKey)?.toJson()"
                }
            } else if value is NSNull {
                flutterPropertyType = "dynamic"
                flutterFromJsonCast = "json['\(key)']"
            } else {
                flutterPropertyType = "dynamic"
            }

            // Flutter 属性声明
            if flutterFramework == "JsonSerializable" {
                if key != camelKey {
                    flutterProperties.append("  @JsonKey(name: '\(key)')")
                }
                flutterProperties.append("  final \(flutterPropertyType)? \(camelKey);")
            } else { // System
                flutterProperties.append("  \(flutterPropertyType)? \(camelKey);")
            }
            flutterConstructorParams.append("this.\(camelKey)")

            // For System fromJson/toJson
            if flutterFramework == "System" {
                flutterFromJsonLines.append("    \(camelKey): \(flutterFromJsonCast),")
                flutterToJsonLines.append("      '\(key)': \(flutterToJsonMapping),")
            }
        } // 结束 for 循环

        // 如果 SwiftyJSON 初始化器已打开，则关闭它
        if swiftFramework == "SwiftyJSON" && swiftInitializerBody.hasPrefix("\n    init") {
            swiftInitializerBody += "    }\n"
        }

        // 生成 Objective-C 接口和实现块内容
        if targetLanguages.contains("objc") {
            var objcModelMethods = ""
            var objcInitMethod = ""
            var objcSynthesizeBlock = ""

            if objcFramework == "MJExtension" {
                if !objcCustomPropertyMappers.isEmpty {
                    objcModelMethods += "\n+ (NSDictionary *)mj_replacedKeyFromPropertyName {\n    return @{\n\(objcCustomPropertyMappers.joined(separator: "\n"))\n    };\n}\n"
                }
                if !objcContainerPropertyGenericClasses.isEmpty {
                    objcModelMethods += "\n+ (NSDictionary *)mj_objectClassInArray {\n    return @{\n\(objcContainerPropertyGenericClasses.joined(separator: "\n"))\n    };\n}\n"
                }
            } else if objcFramework == "YYModel" {
                if !objcCustomPropertyMappers.isEmpty {
                    objcModelMethods += "\n+ (NSDictionary *)modelCustomPropertyMapper {\n    return @{\n\(objcCustomPropertyMappers.joined(separator: "\n"))\n    };\n}\n"
                }
                if !objcContainerPropertyGenericClasses.isEmpty {
                    objcModelMethods += "\n+ (NSDictionary *)modelContainerPropertyGenericClass {\n    return @{\n\(objcContainerPropertyGenericClasses.joined(separator: "\n"))\n    };\n}\n"
                }
            } else { // System
                objcInitMethod = """

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (self) {
\(objcInitAssignments.joined(separator: "\n"))
        // 注意：对于嵌套对象和对象数组，如果不使用 MJExtension/YYModel 等库，
        // 您可能需要在此处实现更具体的转换逻辑。
    }
    return self;
}
"""
                objcSynthesizeBlock = objcSynthesize.joined(separator: "\n")
            }

            allGeneratedObjcHeaders[currentModelName] = """

@interface \(currentModelName) : NSObject
\(objcProperties.joined(separator: "\n"))

\(objcFramework == "System" ? "- (instancetype)initWithDictionary:(NSDictionary *)dictionary;" : "")

@end
""".trimmingCharacters(in: .whitespacesAndNewlines)

            allGeneratedObjcImplementations[currentModelName] = """

@implementation \(currentModelName)
\(objcSynthesizeBlock)
\(objcInitMethod)
\(objcModelMethods)

@end
""".trimmingCharacters(in: .whitespacesAndNewlines)
        }

        // 生成 Swift 结构体/类
        if targetLanguages.contains("swift") {
            var codingKeysBlock = ""
            if swiftFramework == "Codable" && !swiftCodingKeys.isEmpty {
                codingKeysBlock = "\n    enum CodingKeys: String, CodingKey {\n\(swiftCodingKeys.joined(separator: "\n"))\n    }"
            }

            allGeneratedSwiftModels[currentModelName] = """

\(swiftClassOrStructDeclaration) \(currentModelName) \(swiftProtocolConformance) {
\(swiftProperties.joined(separator: "\n"))
\(swiftInitializerBody)
\(codingKeysBlock)
}
"""
        }

        // 生成 Flutter/Dart 类
        if targetLanguages.contains("flutter") {
            var classContent = ""
            if flutterFramework == "JsonSerializable" {
                classContent = """

@JsonSerializable()
class \(currentModelName) {
\(flutterProperties.joined(separator: "\n"))

  \(currentModelName)({\(flutterConstructorParams.joined(separator: ", "))});

  factory \(currentModelName).fromJson(Map<String, dynamic> json) => _$\(currentModelName)FromJson(json);
  Map<String, dynamic> toJson() => _$\(currentModelName)ToJson(this);
}
"""
                // JsonSerializable 的 part 声明只为根模型添加一次
                // 这里使用 `rootModelName` 而不是 `currentModelName` 来确保只为顶层模型生成一次 part 文件名
                // 并确保文件名转换为小写且符合 Dart 命名规范 (例如 `root_model.g.dart`)
                let finalRootModelNameForPart = classNamePrefix + rootModelName
                flutterPartDeclarations.insert("part '\(finalRootModelNameForPart.lowercased()).g.dart';")

            } else { // System
                classContent = """

class \(currentModelName) {
\(flutterProperties.joined(separator: "\n"))

  \(currentModelName)({\(flutterConstructorParams.joined(separator: ", "))});

  factory \(currentModelName).fromJson(Map<String, dynamic> json) {
    return \(currentModelName)(
\(flutterFromJsonLines.joined(separator: "\n"))
    );
  }

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
\(flutterToJsonLines.joined(separator: "\n"))
    };
  }
}
"""
            }
            allGeneratedFlutterModels[currentModelName] = classContent
        }
    } // 结束 processObject 函数

    // 开始处理确定的根对象
    let finalRootModelName = classNamePrefix + rootModelName // 使用 classNamePrefix
    processObject(rootDataForModel, finalRootModelName) // 传递带前缀的根模型名称

    // 组装所有生成的模型以供显示
    if targetLanguages.contains("objc") {
        var objcHeaderContentBlocks: [String] = []
        let sortedOcModelNames = allGeneratedObjcHeaders.keys.sorted()
        for name in sortedOcModelNames {
            objcHeaderContentBlocks.append(allGeneratedObjcHeaders[name]!)
        }

        var globalObjcHeaderImports = Set<String>()
        globalObjcHeaderImports.insert("#import <Foundation/Foundation.h>")
        if objcFramework == "MJExtension" {
            globalObjcHeaderImports.insert("#import <MJExtension/MJExtension.h>")
        } else if objcFramework == "YYModel" {
            globalObjcHeaderImports.insert("#import <YYModel/YYModel.h>")
        }
        generated.objcHeader = globalObjcHeaderImports.joined(separator: "\n") + "\n\n" + objcHeaderContentBlocks.joined(separator: "\n\n")

        var objcImplementationContentBlocks: [String] = []
        for name in sortedOcModelNames {
            objcImplementationContentBlocks.append(allGeneratedObjcImplementations[name]!)
        }
        // 导入主模型的头文件时使用实际的根模型名称 (包含前缀)
        generated.objcImplementation = "#import \"\(finalRootModelName).h\"\n\n" + objcImplementationContentBlocks.joined(separator: "\n\n")
    }

    if targetLanguages.contains("swift") {
        var swiftContentBlocks: [String] = []
        let sortedSwiftModelNames = allGeneratedSwiftModels.keys.sorted()
        for name in sortedSwiftModelNames {
            swiftContentBlocks.append("// MARK: - \(name).swift\n\n\(allGeneratedSwiftModels[name]!)")
        }
        generated.swiftCode = swiftGlobalImports.joined(separator: "\n") + "\n\n" + swiftContentBlocks.joined(separator: "\n\n")
    }

    if targetLanguages.contains("flutter") {
        var flutterContentBlocks: [String] = []
        let sortedFlutterModelNames = allGeneratedFlutterModels.keys.sorted()
        for name in sortedFlutterModelNames {
            flutterContentBlocks.append("// MARK: - \(name).dart\n\n\(allGeneratedFlutterModels[name]!)")
        }

        flutterGlobalImports.insert("import 'dart:convert';")
        if flutterFramework == "JsonSerializable" {
            flutterGlobalImports.insert("import 'package:json_annotation/json_annotation.dart';")
        }

        var finalFlutterCode = flutterGlobalImports.joined(separator: "\n")
        if !flutterPartDeclarations.isEmpty {
            finalFlutterCode += "\n" + flutterPartDeclarations.joined(separator: "\n")
        }
        finalFlutterCode += "\n\n" + flutterContentBlocks.joined(separator: "\n\n")
        generated.flutterCode = finalFlutterCode.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    return generated
}


// MARK: - ViewController Class (视图控制器类)

class ViewController: NSViewController {

    // MARK: - UI Elements (UI 元素)

    // JSON 输入文本区域
    private lazy var jsonInputScrollView: NSScrollView = {
        let scrollView = NSScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.hasVerticalScroller = true
        scrollView.autohidesScrollers = true
        scrollView.borderType = .bezelBorder // 边框样式
        scrollView.documentView = jsonInputTextView
        scrollView.wantsLayer = true // 启用图层以设置圆角
        scrollView.layer?.cornerRadius = 8 // 设置圆角
        scrollView.layer?.masksToBounds = true // 裁剪超出圆角的部分
        return scrollView
    }()

    private lazy var jsonInputTextView: NSTextView = {
        let textView = NSTextView()
        textView.isVerticallyResizable = true
        textView.isHorizontallyResizable = false // 禁止水平滚动
        textView.autoresizingMask = [.width]
        textView.textContainer?.widthTracksTextView = true
        textView.font = NSFont.systemFont(ofSize: 13, weight: .regular)
        textView.backgroundColor = NSColor.textBackgroundColor // 设置背景色
        textView.string = """
{
  "code": 200,
  "msg": "Success",
  "data": {
    "user_id": 123,
    "user_name": "John Doe",
    "is_active": true,
    "balance": 100.50,
    "addresses": [
      {
        "street": "123 Main St",
        "city": "Anytown"
      },
      {
        "street": "456 Oak Ave",
        "city": "Otherville"
      }
    ],
    "profile": {
      "email": "john.doe@example.com",
      "phone_numbers": ["111-222-3333", "444-555-6666"]
    }
  }
}
""" // 默认示例 JSON
        return textView
    }()

    // 根模型名称输入框
    private lazy var modelNameTextField: NSTextField = {
        let textField = NSTextField(frame: .zero)
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.placeholderString = "例如: User, Product"
        textField.font = NSFont.systemFont(ofSize: 14)
        textField.stringValue = "RootModel" // 默认模型名称
        textField.isEditable = true
        textField.bezelStyle = .roundedBezel // 设置圆角边框样式
        textField.wantsLayer = true
        textField.layer?.cornerRadius = 8
        textField.layer?.masksToBounds = true
        return textField
    }()

    // 新增：类名前缀输入框
    private lazy var classNamePrefixTextField: NSTextField = {
        let textField = NSTextField(frame: .zero)
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.placeholderString = "例如: My, API (可选)"
        textField.font = NSFont.systemFont(ofSize: 14)
        textField.stringValue = "" // 默认空
        textField.isEditable = true
        textField.bezelStyle = .roundedBezel
        textField.wantsLayer = true
        textField.layer?.cornerRadius = 8
        textField.layer?.masksToBounds = true
        return textField
    }()

    // AI 建议名称按钮
    private lazy var suggestNameButton: NSButton = {
        let button = NSButton(title: "✨ AI 建议名称", target: self, action: #selector(suggestModelName))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setButtonType(.momentaryPushIn) // 按钮类型
        button.bezelStyle = .rounded
        button.font = NSFont.boldSystemFont(ofSize: 16) // 字体大小与“生成模型”按钮一致
        button.wantsLayer = true
        button.layer?.backgroundColor = NSColor.systemPurple.cgColor // 紫色背景
        button.layer?.cornerRadius = 8
        return button
    }()

    // 生成模型按钮
    private lazy var generateModelButton: NSButton = {
        let button = NSButton(title: "生成模型", target: self, action: #selector(generateModelsAction))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setButtonType(.momentaryPushIn)
        button.bezelStyle = .rounded
        button.font = NSFont.boldSystemFont(ofSize: 16)
        button.wantsLayer = true
        button.layer?.backgroundColor = NSColor.systemBlue.cgColor // 蓝色背景
        button.layer?.cornerRadius = 8
        return button
    }()

    // 建议名称的提示文本
    private lazy var suggestedNameLabel: NSTextField = {
        let label = NSTextField(labelWithString: "")
        label.translatesAutoresizingMaskIntoConstraints = false
        label.isBezeled = false
        label.isEditable = false
        label.drawsBackground = false
        label.font = NSFont.systemFont(ofSize: 12)
        label.textColor = NSColor.gray
        return label
    }()

    // 语言选择（单选按钮）
    private lazy var languageRadioGroup: NSStackView = {
        let stackView = NSStackView()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.orientation = .vertical
        stackView.spacing = 8
        stackView.alignment = .leading
        return stackView
    }()

    private lazy var allLanguageRadio: NSButton = createRadioButton(title: "全部", tag: 0)
    private lazy var objcLanguageRadio: NSButton = createRadioButton(title: "Objective-C", tag: 1)
    private lazy var swiftLanguageRadio: NSButton = createRadioButton(title: "Swift", tag: 2)
    private lazy var flutterLanguageRadio: NSButton = createRadioButton(title: "Flutter/Dart", tag: 3)

    // Swift 框架选择 (下拉菜单)
    private lazy var swiftFrameworkPopUpButton: NSPopUpButton = {
        let button = NSPopUpButton(frame: .zero, pullsDown: false)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addItems(withTitles: ["Codable", "HandyJSON", "SwiftyJSON"])
        button.selectItem(at: 0) // 默认选中 Codable
        return button
    }()

    // Objective-C 框架选择 (下拉菜单)
    private lazy var objcFrameworkPopUpButton: NSPopUpButton = {
        let button = NSPopUpButton(frame: .zero, pullsDown: false)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addItems(withTitles: ["System", "MJExtension", "YYModel"])
        button.selectItem(at: 0) // 默认选中 System
        return button
    }()

    // Flutter 框架选择 (下拉菜单)
    private lazy var flutterFrameworkPopUpButton: NSPopUpButton = {
        let button = NSPopUpButton(frame: .zero, pullsDown: false)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addItems(withTitles: ["System", "JsonSerializable"])
        button.selectItem(at: 0) // 默认选中 System
        return button
    }()

    // FIXED: 为每个框架选择组创建独立的 NSStackView
    private lazy var swiftFrameworkStack: NSStackView = {
        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.spacing = 5
        stack.alignment = .leading
        return stack
    }()

    private lazy var objcFrameworkStack: NSStackView = {
        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.spacing = 5
        stack.alignment = .leading
        return stack
    }()

    private lazy var flutterFrameworkStack: NSStackView = {
        let stack = NSStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.orientation = .vertical
        stack.spacing = 5
        stack.alignment = .leading
        return stack
    }()


    // Objective-C 头文件文本区域
    private lazy var objcHeaderScrollView: NSScrollView = createCodeScrollView()
    private lazy var objcHeaderTextView: NSTextView = createCodeTextView()
    // Objective-C 实现文件文本区域
    private lazy var objcImplementationScrollView: NSScrollView = createCodeScrollView()
    private lazy var objcImplementationTextView: NSTextView = createCodeTextView()
    // Swift 代码文本区域
    private lazy var swiftCodeScrollView: NSScrollView = createCodeScrollView()
    private lazy var swiftCodeTextView: NSTextView = createCodeTextView()
    // Flutter 代码文本区域
    private lazy var flutterCodeScrollView: NSScrollView = createCodeScrollView()
    private lazy var flutterCodeTextView: NSTextView = createCodeTextView()

    // 错误信息标签
    private lazy var errorLabel: NSTextField = {
        let label = NSTextField(labelWithString: "")
        label.translatesAutoresizingMaskIntoConstraints = false
        label.isBezeled = false
        label.isEditable = false
        label.drawsBackground = false
        label.font = NSFont.systemFont(ofSize: 13, weight: .semibold)
        label.textColor = NSColor.systemRed
        label.alignment = .center
        label.isHidden = true
        return label
    }()

    // 加载指示器
    private lazy var loadingIndicator: NSProgressIndicator = {
        let indicator = NSProgressIndicator()
        indicator.translatesAutoresizingMaskIntoConstraints = false
        indicator.style = .spinning // 旋转样式
        indicator.controlSize = .small // 小尺寸
        indicator.isHidden = true // 默认隐藏
        return indicator
    }()

    // AI 解释模型按钮
    private lazy var explainModelButton: NSButton = {
        let button = NSButton(title: "✨ 解释模型", target: self, action: #selector(explainModel))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setButtonType(.momentaryPushIn)
        button.bezelStyle = .rounded
        button.font = NSFont.boldSystemFont(ofSize: 14)
        button.wantsLayer = true
        button.layer?.backgroundColor = NSColor.systemGreen.cgColor // 绿色背景
        button.layer?.cornerRadius = 8
        button.isHidden = true // 默认隐藏，有 Swift 代码时才显示
        return button
    }()

    // 模型解释文本区域
    private lazy var modelExplanationScrollView: NSScrollView = {
        let scrollView = NSScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.hasVerticalScroller = true
        scrollView.autohidesScrollers = true
        scrollView.borderType = .bezelBorder
        scrollView.documentView = modelExplanationTextView
        scrollView.wantsLayer = true
        scrollView.layer?.cornerRadius = 8
        scrollView.layer?.masksToBounds = true
        scrollView.isHidden = true
        return scrollView
    }()

    private lazy var modelExplanationTextView: NSTextView = {
        let textView = NSTextView()
        textView.isVerticallyResizable = true
        textView.isHorizontallyResizable = false
        textView.autoresizingMask = [.width]
        textView.textContainer?.widthTracksTextView = true
        textView.font = NSFont.systemFont(ofSize: 13)
        textView.backgroundColor = NSColor.controlBackgroundColor // 使用系统默认背景色
        textView.isEditable = false
        textView.textColor = NSColor.darkGray
        return textView
    }()

    // 用于管理代码输出视图的字典
    private var codeOutputViews: [String: (scrollView: NSScrollView, textView: NSTextView)] = [:]

    // 新增：声明 mainHorizontalStackView 为类属性
    private lazy var mainHorizontalStackView: NSStackView = {
        let stackView = NSStackView()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.orientation = .horizontal // 水平排列
        stackView.distribution = .fill // 更改为 .fill，以便更灵活地管理子视图宽度
        stackView.spacing = 30 // 增加列之间的间距
        stackView.alignment = .top // 顶部对齐
        return stackView
    }()

    // 新增：声明 codeOutputStack 为类属性
    private lazy var codeOutputStack: NSStackView = {
        let stackView = NSStackView()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.orientation = .vertical
        stackView.spacing = 15
        stackView.alignment = .leading
        stackView.distribution = .fill // 保持 .fill
        return stackView
    }()

    // 当前选中的语言（tag 值）
    private var selectedLanguageTag: Int = 0 { // 0: 全部, 1: OC, 2: Swift, 3: Flutter
        didSet {
            updateCodeOutputVisibility() // 语言选择改变时更新显示
        }
    }

    // Gemini API 密钥 - 实际应用中应安全存储和加载
    // TODO: 请将此处的空字符串替换为您的实际 Gemini API 密钥。
    // 例如：private let apiKey = "AIzaSyCvKgb0Vj51EbpIrWlY9vMqnZAk_oFsXr0"
    private let apiKey = "AIzaSyCvKgb0Vj51EbpIrWlY9vMqnZAk_oFsXr0"

    // MARK: - View Lifecycle (视图生命周期)

    override func loadView() {
        // 创建主视图
        self.view = NSView()
        self.view.wantsLayer = true // 启用图层
        self.view.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor // 设置背景颜色
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI() // 设置用户界面
        setupEventHandlers() // 设置事件处理
        updateCodeOutputVisibility() // 初始设置代码输出视图可见性
    }

    // MARK: - UI Setup (UI 设置)

    private func setupUI() {
        // 确保所有视图都设置为使用自动布局
        view.translatesAutoresizingMaskIntoConstraints = false

        // 创建顶部标题标签
        let titleLabel = NSTextField(labelWithString: "JSON 数据模型生成器")
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.font = NSFont.boldSystemFont(ofSize: 24)
        titleLabel.alignment = .center
        view.addSubview(titleLabel)

        // 错误信息标签
        view.addSubview(errorLabel)

        // 添加主水平堆栈视图
        view.addSubview(mainHorizontalStackView)

        // --- 左侧列: JSON 输入区域 ---
        let jsonInputColumn = NSStackView()
        jsonInputColumn.translatesAutoresizingMaskIntoConstraints = false
        jsonInputColumn.orientation = .vertical
        jsonInputColumn.spacing = 10
        jsonInputColumn.alignment = .leading
        jsonInputColumn.edgeInsets = NSEdgeInsets(top: 15, left: 15, bottom: 15, right: 15) // 内边距

        let jsonInputTitle = NSTextField(labelWithString: "JSON 数据输入区域")
        jsonInputTitle.font = NSFont.boldSystemFont(ofSize: 16)
        jsonInputTitle.isBezeled = false
        jsonInputTitle.isEditable = false
        jsonInputTitle.drawsBackground = false
        jsonInputColumn.addArrangedSubview(jsonInputTitle)

        let jsonInputLabel = NSTextField(labelWithString: "粘贴你的 JSON 数据:")
        jsonInputLabel.font = NSFont.systemFont(ofSize: 13)
        jsonInputLabel.isBezeled = false
        jsonInputLabel.isEditable = false
        jsonInputLabel.drawsBackground = false
        jsonInputColumn.addArrangedSubview(jsonInputLabel)

        jsonInputColumn.addArrangedSubview(jsonInputScrollView)
        // jsonInputScrollView 应该填充剩余垂直空间
        jsonInputScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 200).isActive = true
        jsonInputScrollView.widthAnchor.constraint(equalTo: jsonInputColumn.widthAnchor).isActive = true

        mainHorizontalStackView.addArrangedSubview(jsonInputColumn)


        // --- 中间列: 生成代码区域和控制按钮 ---
        let centerColumn = NSStackView()
        centerColumn.translatesAutoresizingMaskIntoConstraints = false
        centerColumn.orientation = .vertical
        centerColumn.spacing = 15
        centerColumn.alignment = .centerX
        centerColumn.edgeInsets = NSEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)

        let generatedCodeTitle = NSTextField(labelWithString: "生成的代码区域")
        generatedCodeTitle.font = NSFont.boldSystemFont(ofSize: 16)
        generatedCodeTitle.isBezeled = false
        generatedCodeTitle.isEditable = false
        generatedCodeTitle.drawsBackground = false
        centerColumn.addArrangedSubview(generatedCodeTitle)

        // 模型名称输入和建议按钮的垂直堆栈
        let modelNameControlsStack = NSStackView()
        modelNameControlsStack.translatesAutoresizingMaskIntoConstraints = false
        modelNameControlsStack.orientation = .vertical // 垂直排列
        modelNameControlsStack.spacing = 10
        modelNameControlsStack.alignment = .leading // 左对齐

        let modelNameLabel = NSTextField(labelWithString: "根模型名称:")
        modelNameLabel.isBezeled = false
        modelNameLabel.isEditable = false
        modelNameLabel.drawsBackground = false
        modelNameControlsStack.addArrangedSubview(modelNameLabel)
        
        // 将输入框直接添加到 modelNameControlsStack
        modelNameControlsStack.addArrangedSubview(modelNameTextField)
        // 调整根模型名称输入框的宽度和高度，使其与类名前缀输入框一致
        modelNameTextField.widthAnchor.constraint(equalTo: modelNameControlsStack.widthAnchor).isActive = true
        modelNameTextField.heightAnchor.constraint(equalToConstant: 30).isActive = true // 假设类名前缀输入框高度为30

        // 将 AI 建议名称按钮放到输入框下方
        modelNameControlsStack.addArrangedSubview(suggestNameButton)
        suggestNameButton.widthAnchor.constraint(equalTo: modelNameControlsStack.widthAnchor).isActive = true // 按钮宽度填充堆栈
        suggestNameButton.heightAnchor.constraint(equalToConstant: 40).isActive = true // 按钮高度与“生成模型”按钮一致

        centerColumn.addArrangedSubview(modelNameControlsStack)
        modelNameControlsStack.widthAnchor.constraint(equalTo: centerColumn.widthAnchor, multiplier: 0.95).isActive = true // 限制宽度

        centerColumn.addArrangedSubview(suggestedNameLabel) // AI 建议名称显示

        // 新增：类名前缀标签和输入框
        let classNamePrefixLabel = NSTextField(labelWithString: "类名前缀 (可选):")
        classNamePrefixLabel.font = NSFont.systemFont(ofSize: 13)
        classNamePrefixLabel.isBezeled = false
        classNamePrefixLabel.isEditable = false
        classNamePrefixLabel.drawsBackground = false
        centerColumn.addArrangedSubview(classNamePrefixLabel)
        centerColumn.addArrangedSubview(classNamePrefixTextField)
        classNamePrefixTextField.widthAnchor.constraint(equalTo: centerColumn.widthAnchor, multiplier: 0.95).isActive = true // 限制宽度
        classNamePrefixTextField.heightAnchor.constraint(equalToConstant: 30).isActive = true // 确保高度一致

        // 生成模型按钮
        centerColumn.addArrangedSubview(generateModelButton)
        generateModelButton.widthAnchor.constraint(equalTo: centerColumn.widthAnchor, multiplier: 0.8).isActive = true // 按钮宽度
        generateModelButton.heightAnchor.constraint(equalToConstant: 40).isActive = true // 确保高度一致

        // 加载指示器
        centerColumn.addArrangedSubview(loadingIndicator)

        // 添加代码输出区域容器（垂直堆栈）
        centerColumn.addArrangedSubview(codeOutputStack)
        // codeOutputStack 的子视图现在在 addCodeOutputView 中添加
        codeOutputStack.widthAnchor.constraint(equalTo: centerColumn.widthAnchor).isActive = true
        codeOutputStack.heightAnchor.constraint(greaterThanOrEqualToConstant: 400).isActive = true // 确保代码输出区域有最小高度

        codeOutputViews["objcHeader"] = (objcHeaderScrollView, objcHeaderTextView)
        codeOutputViews["objcImplementation"] = (objcImplementationScrollView, objcImplementationTextView)
        codeOutputViews["swiftCode"] = (swiftCodeScrollView, swiftCodeTextView)
        codeOutputViews["flutterCode"] = (flutterCodeScrollView, flutterCodeTextView)

        // 添加带标题的滚动视图到输出堆栈
        addCodeOutputView(to: codeOutputStack, scrollView: objcHeaderScrollView, textView: objcHeaderTextView, title: "Objective-C (.h)", copyAction: #selector(copyObjcHeaderCode))
        addCodeOutputView(to: codeOutputStack, scrollView: objcImplementationScrollView, textView: objcImplementationTextView, title: "Objective-C (.m)", copyAction: #selector(copyObjcImplementationCode))
        addCodeOutputView(to: codeOutputStack, scrollView: swiftCodeScrollView, textView: swiftCodeTextView, title: "Swift (.swift)", copyAction: #selector(copySwiftCode))
        addCodeOutputView(to: codeOutputStack, scrollView: flutterCodeScrollView, textView: flutterCodeTextView, title: "Flutter/Dart (.dart)", copyAction: #selector(copyFlutterCode))

        // AI 解释模型按钮和解释文本区域
        centerColumn.addArrangedSubview(explainModelButton)
        explainModelButton.widthAnchor.constraint(equalTo: centerColumn.widthAnchor, multiplier: 0.8).isActive = true
        centerColumn.addArrangedSubview(modelExplanationScrollView)
        modelExplanationScrollView.widthAnchor.constraint(equalTo: centerColumn.widthAnchor).isActive = true
        modelExplanationScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 100).isActive = true

        mainHorizontalStackView.addArrangedSubview(centerColumn)


        // --- 右侧列: 语言和框架选择区域 ---
        let rightColumn = NSStackView()
        rightColumn.translatesAutoresizingMaskIntoConstraints = false
        rightColumn.orientation = .vertical
        rightColumn.spacing = 15
        rightColumn.alignment = .leading
        rightColumn.edgeInsets = NSEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)

        let languageFrameworkTitle = NSTextField(labelWithString: "语言和第三方库选择区域")
        languageFrameworkTitle.font = NSFont.boldSystemFont(ofSize: 16)
        languageFrameworkTitle.isBezeled = false
        languageFrameworkTitle.isEditable = false
        languageFrameworkTitle.drawsBackground = false
        rightColumn.addArrangedSubview(languageFrameworkTitle)

        // 语言选择组
        let languageSelectionLabel = NSTextField(labelWithString: "选择生成语言:")
        languageSelectionLabel.font = NSFont.systemFont(ofSize: 13)
        languageSelectionLabel.isBezeled = false
        languageSelectionLabel.isEditable = false
        languageSelectionLabel.drawsBackground = false
        rightColumn.addArrangedSubview(languageSelectionLabel)

        languageRadioGroup.addArrangedSubview(allLanguageRadio)
        languageRadioGroup.addArrangedSubview(objcLanguageRadio)
        languageRadioGroup.addArrangedSubview(swiftLanguageRadio)
        languageRadioGroup.addArrangedSubview(flutterLanguageRadio)
        rightColumn.addArrangedSubview(languageRadioGroup)
        allLanguageRadio.state = .on // 默认选中“全部”

        // FIXED: 将 Swift 框架选择组添加到其独立的堆栈视图，然后将堆栈视图添加到右侧列
        let swiftFrameworkLabel = NSTextField(labelWithString: "Swift 框架:")
        swiftFrameworkLabel.isBezeled = false; swiftFrameworkLabel.isEditable = false; swiftFrameworkLabel.drawsBackground = false; swiftFrameworkLabel.font = NSFont.systemFont(ofSize: 13)
        swiftFrameworkStack.addArrangedSubview(swiftFrameworkLabel)
        swiftFrameworkStack.addArrangedSubview(swiftFrameworkPopUpButton)
        rightColumn.addArrangedSubview(swiftFrameworkStack)

        // FIXED: 将 Objective-C 框架选择组添加到其独立的堆栈视图，然后将堆栈视图添加到右侧列
        let objcFrameworkLabel = NSTextField(labelWithString: "Objective-C 框架:")
        objcFrameworkLabel.isBezeled = false; objcFrameworkLabel.isEditable = false; objcFrameworkLabel.drawsBackground = false; objcFrameworkLabel.font = NSFont.systemFont(ofSize: 13)
        objcFrameworkStack.addArrangedSubview(objcFrameworkLabel)
        objcFrameworkStack.addArrangedSubview(objcFrameworkPopUpButton)
        rightColumn.addArrangedSubview(objcFrameworkStack)

        // FIXED: 将 Flutter 框架选择组添加到其独立的堆栈视图，然后将堆栈视图添加到右侧列
        let flutterFrameworkLabel = NSTextField(labelWithString: "Flutter/Dart 框架:")
        flutterFrameworkLabel.isBezeled = false; flutterFrameworkLabel.isEditable = false; flutterFrameworkLabel.drawsBackground = false; flutterFrameworkLabel.font = NSFont.systemFont(ofSize: 13)
        flutterFrameworkStack.addArrangedSubview(flutterFrameworkLabel)
        flutterFrameworkStack.addArrangedSubview(flutterFrameworkPopUpButton)
        rightColumn.addArrangedSubview(flutterFrameworkStack)

        mainHorizontalStackView.addArrangedSubview(rightColumn)

        // MARK: - AutoLayout Constraints (自动布局约束)

        // 顶部标题约束
        NSLayoutConstraint.activate([
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            titleLabel.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, multiplier: 0.9)
        ])

        // 错误信息标签约束
        NSLayoutConstraint.activate([
            errorLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
            errorLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            errorLabel.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, multiplier: 0.9)
        ])

        // 主水平堆栈视图约束 - 确保宽度和高度充满父视图
        NSLayoutConstraint.activate([
            // 恢复为 20，以避免顶部内容被遮挡
            mainHorizontalStackView.topAnchor.constraint(equalTo: errorLabel.bottomAnchor, constant: 20),
            mainHorizontalStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            mainHorizontalStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            mainHorizontalStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
            // 确保总宽度有一个合理的最小值，以防止窗口变窄
            mainHorizontalStackView.widthAnchor.constraint(greaterThanOrEqualToConstant: 1100) // 增加最小宽度
        ])

        // FIXED: 为左右两列设置固定宽度，以防止其在切换语言时收缩
        jsonInputColumn.widthAnchor.constraint(equalToConstant: 350).isActive = true
        rightColumn.widthAnchor.constraint(equalToConstant: 300).isActive = true
        
        // 中间列设置为可以根据内容压缩和抱负，让它来填补剩余空间
        centerColumn.setContentHuggingPriority(.defaultLow, for: .horizontal)
        centerColumn.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

        // 确保列的垂直方向填充其父视图
        jsonInputColumn.heightAnchor.constraint(equalTo: mainHorizontalStackView.heightAnchor).isActive = true
        centerColumn.heightAnchor.constraint(equalTo: mainHorizontalStackView.heightAnchor).isActive = true
        rightColumn.heightAnchor.constraint(equalTo: mainHorizontalStackView.heightAnchor).isActive = true

        // 调整 jsonInputScrollView 和 codeOutputStack 的垂直填充行为
        // 恢复为 -100，以确保输入区域有足够的显示空间
        jsonInputScrollView.heightAnchor.constraint(equalTo: jsonInputColumn.heightAnchor, constant: -100).isActive = true
        jsonInputScrollView.setContentCompressionResistancePriority(.defaultLow, for: .vertical) // 允许垂直压缩

        codeOutputStack.heightAnchor.constraint(equalTo: centerColumn.heightAnchor, constant: -250).isActive = true // 减去顶部控件高度
        codeOutputStack.setContentCompressionResistancePriority(.defaultLow, for: .vertical) // 允许垂直压缩

        // 确保各个代码输出文本视图能够垂直拉伸
        objcHeaderScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true // 最小高度
        objcImplementationScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
        swiftCodeScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
        flutterCodeScrollView.heightAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true

        // 设置每个 code output scroll view 的垂直内容抱负优先级为低，允许它们拉伸
        objcHeaderScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
        objcImplementationScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
        swiftCodeScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
        flutterCodeScrollView.setContentHuggingPriority(.defaultLow, for: .vertical)
    }

    // MARK: - Helper UI Creation (辅助 UI 创建)

    // 创建带圆角和背景色的滚动文本视图
    private func createCodeScrollView() -> NSScrollView {
        let scrollView = NSScrollView()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.hasVerticalScroller = true
        scrollView.autohidesScrollers = true
        scrollView.borderType = .bezelBorder
        scrollView.wantsLayer = true
        scrollView.layer?.cornerRadius = 8
        scrollView.layer?.masksToBounds = true
        scrollView.layer?.backgroundColor = NSColor.init(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0).cgColor // 深色背景
        return scrollView
    }

    // 创建代码文本视图
    private func createCodeTextView() -> NSTextView {
        let textView = NSTextView()
        textView.isVerticallyResizable = true
        textView.isHorizontallyResizable = false
        textView.autoresizingMask = [.width]
        textView.textContainer?.widthTracksTextView = true
        textView.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular) // 等宽字体
        textView.backgroundColor = .clear // 透明背景，使用 scroll view 的背景
        textView.isEditable = false // 默认不可编辑
        textView.textColor = NSColor.systemGreen // 绿色文本
        textView.isSelectable = true // 可选择
        return textView
    }

    // 添加代码输出视图（带标题和复制按钮）
    private func addCodeOutputView(to stackView: NSStackView, scrollView: NSScrollView, textView: NSTextView, title: String, copyAction: Selector) {
        let containerStack = NSStackView()
        containerStack.translatesAutoresizingMaskIntoConstraints = false
        containerStack.orientation = .vertical
        containerStack.spacing = 5
        containerStack.alignment = .leading
        containerStack.distribution = .fill

        let headerStack = NSStackView()
        headerStack.translatesAutoresizingMaskIntoConstraints = false
        headerStack.orientation = .horizontal
        headerStack.spacing = 10
        headerStack.alignment = .centerY
        headerStack.distribution = .fill

        let titleLabel = NSTextField(labelWithString: title)
        titleLabel.font = NSFont.boldSystemFont(ofSize: 14)
        titleLabel.isBezeled = false
        titleLabel.isEditable = false
        titleLabel.drawsBackground = false
        headerStack.addArrangedSubview(titleLabel)

        let copyButton = NSButton(title: "复制", target: self, action: copyAction)
        copyButton.setButtonType(.momentaryPushIn)
        copyButton.bezelStyle = .rounded
        copyButton.controlSize = .small
        copyButton.font = NSFont.systemFont(ofSize: 11)
        headerStack.addArrangedSubview(copyButton)

        containerStack.addArrangedSubview(headerStack)
        // 使头部堆栈宽度与容器堆栈相同，确保按钮不会溢出
        headerStack.widthAnchor.constraint(equalTo: containerStack.widthAnchor).isActive = true

        scrollView.documentView = textView // 将文本视图设置为滚动视图的文档视图
        containerStack.addArrangedSubview(scrollView)
        // 移除固定的 heightAnchor，让它根据内容或父视图拉伸
        // scrollView.heightAnchor.constraint(equalToConstant: 150).isActive = true // FIXED: Removed fixed height
        scrollView.widthAnchor.constraint(equalTo: containerStack.widthAnchor).isActive = true

        stackView.addArrangedSubview(containerStack)
        containerStack.widthAnchor.constraint(equalTo: stackView.widthAnchor).isActive = true
    }

    // 创建单选按钮
    private func createRadioButton(title: String, tag: Int) -> NSButton {
        let button = NSButton(radioButtonWithTitle: title, target: self, action: #selector(languageRadioChanged(_:)))
        button.translatesAutoresizingMaskIntoConstraints = false
        button.tag = tag // 设置标签以便识别
        return button
    }


    // MARK: - Event Handlers (事件处理)

    private func setupEventHandlers() {
        // 设置所有单选按钮的 target/action
        allLanguageRadio.target = self
        allLanguageRadio.action = #selector(languageRadioChanged(_:))
        objcLanguageRadio.target = self
        objcLanguageRadio.action = #selector(languageRadioChanged(_:))
        swiftLanguageRadio.target = self
        swiftLanguageRadio.action = #selector(languageRadioChanged(_:))
        flutterLanguageRadio.target = self
        flutterLanguageRadio.action = #selector(languageRadioChanged(_:))

        // 为下拉菜单添加 action
        swiftFrameworkPopUpButton.target = self
        swiftFrameworkPopUpButton.action = #selector(frameworkSelectionChanged)
        objcFrameworkPopUpButton.target = self
        objcFrameworkPopUpButton.action = #selector(frameworkSelectionChanged)
        flutterFrameworkPopUpButton.target = self
        flutterFrameworkPopUpButton.action = #selector(frameworkSelectionChanged)
    }

    // 处理语言选择单选按钮的变化
    @objc private func languageRadioChanged(_ sender: NSButton) {
        selectedLanguageTag = sender.tag
        // 确保同一组的按钮只有 sender 被选中
        [allLanguageRadio, objcLanguageRadio, swiftLanguageRadio, flutterLanguageRadio].forEach { btn in
            if btn != sender {
                btn.state = .off
            }
        }
        updateFrameworkVisibility() // 更新框架下拉菜单的可见性

        // Update code output visibility (this also calls updateFrameworkVisibility internally)
        updateCodeOutputVisibility()

        // 关键：手动触发父视图的布局更新，特别是当 arrangedSubviews 的isHidden属性改变时
        // 从最内层受影响的堆栈视图开始，向外层传播布局更新
        codeOutputStack.needsLayout = true
        codeOutputStack.layoutSubtreeIfNeeded()

        if let centerColumn = codeOutputStack.superview as? NSStackView {
            centerColumn.needsLayout = true
            centerColumn.layoutSubtreeIfNeeded()
        }
        mainHorizontalStackView.needsLayout = true
        mainHorizontalStackView.layoutSubtreeIfNeeded()
    }

    // 处理框架选择下拉菜单的变化 (这里仅仅触发 generateModelsAction 重新生成)
    @objc private func frameworkSelectionChanged() {
        generateModelsAction()
    }

    // 更新代码输出视图的可见性
    private func updateCodeOutputVisibility() {
        let isAllSelected = (selectedLanguageTag == 0)
        let isObjcSelected = (selectedLanguageTag == 1)
        let isSwiftSelected = (selectedLanguageTag == 2)
        let isFlutterSelected = (selectedLanguageTag == 3)

        // 根据语言选择控制各个代码输出区域的可见性
        objcHeaderScrollView.superview?.isHidden = !(isAllSelected || isObjcSelected)
        objcImplementationScrollView.superview?.isHidden = !(isAllSelected || isObjcSelected)
        swiftCodeScrollView.superview?.isHidden = !(isAllSelected || isSwiftSelected)
        flutterCodeScrollView.superview?.isHidden = !(isAllSelected || isFlutterSelected)

        // 仅当 Swift 代码可见时才显示解释模型按钮
        explainModelButton.isHidden = !(isAllSelected || isSwiftSelected) || swiftCodeTextView.string.isEmpty
        modelExplanationScrollView.isHidden = explainModelButton.isHidden || modelExplanationTextView.string.isEmpty

        // 同时更新框架选择的可见性
        updateFrameworkVisibility()
    }

    // 更新框架选择下拉菜单的可见性
    private func updateFrameworkVisibility() {
        let isAllSelected = (selectedLanguageTag == 0)
        let isObjcSelected = (selectedLanguageTag == 1)
        let isSwiftSelected = (selectedLanguageTag == 2)
        let isFlutterSelected = (selectedLanguageTag == 3)

        // FIXED: 隐藏/显示独立的框架堆栈，而不是它们的内容。
        swiftFrameworkStack.isHidden = !(isAllSelected || isSwiftSelected)
        objcFrameworkStack.isHidden = !(isAllSelected || isObjcSelected)
        flutterFrameworkStack.isHidden = !(isAllSelected || isFlutterSelected)
    }


    // MARK: - Core Actions (核心操作)

    // 生成模型按钮点击事件
    @objc private func generateModelsAction() {
        errorLabel.isHidden = true
        errorLabel.stringValue = ""
        loadingIndicator.isHidden = false
        loadingIndicator.startAnimation(nil)

        // 清除所有之前的输出
        objcHeaderTextView.string = ""
        objcImplementationTextView.string = ""
        swiftCodeTextView.string = ""
        flutterCodeTextView.string = ""
        suggestedNameLabel.stringValue = ""
        modelExplanationTextView.string = ""
        modelExplanationScrollView.isHidden = true // 隐藏解释区域

        // 获取当前选中的语言
        var selectedLanguages: Set<String> = []
        switch selectedLanguageTag {
        case 0: selectedLanguages = ["objc", "swift", "flutter"] // 全部
        case 1: selectedLanguages = ["objc"]
        case 2: selectedLanguages = ["swift"]
        case 3: selectedLanguages = ["flutter"]
        default: selectedLanguages = ["objc", "swift", "flutter"]
        }

        // 获取选中的框架
        let currentSwiftFramework = swiftFrameworkPopUpButton.titleOfSelectedItem ?? "Codable"
        let currentObjcFramework = objcFrameworkPopUpButton.titleOfSelectedItem ?? "System"
        let currentFlutterFramework = flutterFrameworkPopUpButton.titleOfSelectedItem ?? "System"
        let currentClassNamePrefix = classNamePrefixTextField.stringValue // 获取类名前缀

        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            do {
                let generatedCode = try generateModels(
                    jsonDataString: self.jsonInputTextView.string,
                    rootModelName: self.modelNameTextField.stringValue,
                    classNamePrefix: currentClassNamePrefix, // 传递类名前缀
                    targetLanguages: selectedLanguages,
                    swiftFramework: currentSwiftFramework,
                    objcFramework: currentObjcFramework,
                    flutterFramework: currentFlutterFramework
                )

                DispatchQueue.main.async {
                    self.objcHeaderTextView.string = generatedCode.objcHeader
                    self.objcImplementationTextView.string = generatedCode.objcImplementation
                    self.swiftCodeTextView.string = generatedCode.swiftCode
                    self.flutterCodeTextView.string = generatedCode.flutterCode
                    self.loadingIndicator.stopAnimation(nil)
                    self.loadingIndicator.isHidden = true
                    self.updateCodeOutputVisibility() // 更新按钮和解释区域可见性
                }
            } catch let error as NSError {
                DispatchQueue.main.async {
                    self.errorLabel.stringValue = "错误: \(error.localizedDescription)"
                    self.errorLabel.isHidden = false
                    self.loadingIndicator.stopAnimation(nil)
                    self.loadingIndicator.isHidden = true
                }
            } catch {
                DispatchQueue.main.async {
                    self.errorLabel.stringValue = "发生未知错误。"
                    self.errorLabel.isHidden = false
                    self.loadingIndicator.stopAnimation(nil)
                    self.loadingIndicator.isHidden = true
                }
            }
        }
    }

    // AI 建议模型名称按钮点击事件
    @objc private func suggestModelName() {
        guard !jsonInputTextView.string.isEmpty else {
            errorLabel.stringValue = "请先粘贴 JSON 数据以获取建议。"
            errorLabel.isHidden = false
            return
        }

        suggestNameButton.isEnabled = false // 禁用按钮防止重复点击
        loadingIndicator.isHidden = false
        loadingIndicator.startAnimation(nil)
        suggestedNameLabel.stringValue = "建议中..."

        let prompt = "Given the following JSON data, what would be the most appropriate and descriptive root model name? Provide only the suggested name, no other content. JSON: \n\n```json\n\(jsonInputTextView.string)\n```"

        // Gemini API 请求
        fetchGeminiResponse(prompt: prompt) { [weak self] result in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.loadingIndicator.stopAnimation(nil)
                self.loadingIndicator.isHidden = true
                self.suggestNameButton.isEnabled = true // 重新启用按钮

                switch result {
                case .success(let text):
                    var suggested = text.trimmingCharacters(in: .whitespacesAndNewlines)
                    // 清理常见的 LLM 响应格式
                    suggested = suggested.replacingOccurrences(of: "^```[a-zA-Z]*\\s*|\\s*```$", with: "", options: .regularExpression)
                    suggested = suggested.replacingOccurrences(of: "[\"'.]", with: "", options: .regularExpression)
                    suggested = capitalizeFirstLetter(suggested) // 将建议名称的首字母大写
                    self.suggestedNameLabel.stringValue = "AI 建议: \(suggested)"
                    self.modelNameTextField.stringValue = suggested // 自动填充输入框
                case .failure(let error):
                    self.suggestedNameLabel.stringValue = "未能获取建议名称。"
                    self.errorLabel.stringValue = "获取建议名称时出错: \(error.localizedDescription)"
                    self.errorLabel.isHidden = false
                }
            }
        }
    }

    // 解释模型按钮点击事件
    @objc private func explainModel() {
        guard !swiftCodeTextView.string.isEmpty else {
            errorLabel.stringValue = "请先生成模型代码以获取解释。"
            errorLabel.isHidden = false
            return
        }

        explainModelButton.isEnabled = false // 禁用按钮防止重复点击
        loadingIndicator.isHidden = false
        loadingIndicator.startAnimation(nil)
        modelExplanationScrollView.isHidden = false // 显示解释区域
        modelExplanationTextView.string = "解释中..."

        let prompt = "Explain the structure and purpose of the following Swift data model in a concise and easy-to-understand manner. Provide only the explanation, no code or other formatting. Swift model:\n\n```swift\n\(swiftCodeTextView.string)\n```"

        // Gemini API 请求
        fetchGeminiResponse(prompt: prompt) { [weak self] result in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.loadingIndicator.stopAnimation(nil)
                self.loadingIndicator.isHidden = true
                self.explainModelButton.isEnabled = true // 重新启用按钮

                switch result {
                case .success(let text):
                    self.modelExplanationTextView.string = text.trimmingCharacters(in: .whitespacesAndNewlines)
                case .failure(let error):
                    self.modelExplanationTextView.string = "未能获取模型解释。"
                    self.errorLabel.stringValue = "获取模型解释时出错: \(error.localizedDescription)"
                    self.errorLabel.isHidden = false
                }
            }
        }
    }

    // MARK: - Clipboard Actions (剪贴板操作)

    @objc private func copyObjcHeaderCode() {
        copyToClipboard(text: objcHeaderTextView.string)
    }

    @objc private func copyObjcImplementationCode() {
        copyToClipboard(text: objcImplementationTextView.string)
    }

    @objc private func copySwiftCode() {
        copyToClipboard(text: swiftCodeTextView.string)
    }

    @objc private func copyFlutterCode() {
        copyToClipboard(text: flutterCodeTextView.string)
    }

    private func copyToClipboard(text: String) {
        let pasteboard = NSPasteboard.general
        pasteboard.clearContents() // 清空剪贴板内容
        pasteboard.setString(text, forType: .string) // 设置字符串类型内容
        // 可以在这里添加一个短暂的 UI 提示，例如一个 NSTextField 动画显示“已复制！”
        showAlert(message: "代码已复制到剪贴板！")
    }

    // MARK: - Gemini API Call (Gemini API 调用)

    private func fetchGeminiResponse(prompt: String, completion: @escaping (Result<String, Error>) -> Void) {
        let chatHistory: [[String: Any]] = [["role": "user", "parts": [["text": prompt]]]]
        let payload: [String: Any] = ["contents": chatHistory]

        guard let url = URL(string: "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=\(apiKey)") else {
            completion(.failure(NSError(domain: "NetworkError", code: 4, userInfo: [NSLocalizedDescriptionKey: "无效的 API URL。"])))
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: payload, options: [])
        } catch {
            completion(.failure(NSError(domain: "NetworkError", code: 5, userInfo: [NSLocalizedDescriptionKey: "无法序列化请求体：\(error.localizedDescription)"])))
            return
        }

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("❌ 网络请求失败，错误：\(error.localizedDescription)")
                if let nsError = error as? NSError {
                    print("错误域：\(nsError.domain)，代码：\(nsError.code)")
                    if let userInfo = nsError.userInfo as? [String: Any] {
                        userInfo.forEach { key, value in
                            print("用户信息 - \(key)：\(value)")
                        }
                    }
                }
                completion(.failure(error))
                return
            }

            guard let httpResponse = response as? HTTPURLResponse else {
                print("❌ 响应不是 HTTPURLResponse。")
                completion(.failure(NSError(domain: "NetworkError", code: 9, userInfo: [NSLocalizedDescriptionKey: "非 HTTP 响应。"])))
                return
            }

            print("✅ HTTP 状态码：\(httpResponse.statusCode)")
            if let data = data {
                print("接收数据大小：\(data.count) 字节")
                // 可选：如果数据量小且是文本，可以打印字符串形式的数据进行调试
                // if let responseString = String(data: data, encoding: .utf8) {
                //     print("响应数据 (字符串)：\(responseString)")
                // }
            } else {
                print("未接收到数据。")
            }

            guard let data = data else {
                completion(.failure(NSError(domain: "NetworkError", code: 6, userInfo: [NSLocalizedDescriptionKey: "未收到数据。"])))
                return
            }

            do {
                if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let candidates = jsonResponse["candidates"] as? [[String: Any]],
                   let firstCandidate = candidates.first,
                   let content = firstCandidate["content"] as? [String: Any],
                   let parts = content["parts"] as? [[String: Any]],
                   let firstPart = parts.first,
                   let text = firstPart["text"] as? String {
                    completion(.success(text))
                } else {
                    print("❌ API 响应格式异常或内容缺失。")
                    if let responseString = String(data: data, encoding: .utf8) {
                        print("原始 API 响应：\(responseString)")
                    }
                    completion(.failure(NSError(domain: "APIError", code: 7, userInfo: [NSLocalizedDescriptionKey: "API 响应格式异常或内容缺失。"])))
                }
            } catch {
                print("❌ 无法解析 API 响应 JSON：\(error.localizedDescription)")
                if let responseString = String(data: data, encoding: .utf8) {
                    print("解析失败的原始数据：\(responseString)")
                }
                completion(.failure(NSError(domain: "APIError", code: 8, userInfo: [NSLocalizedDescriptionKey: "无法解析 API 响应：\(error.localizedDescription)"])))
            }
        }
        task.resume()
    }

    // MARK: - Alert Helper (警告框辅助)

    private func showAlert(message: String) {
        let alert = NSAlert()
        alert.messageText = "信息"
        alert.informativeText = message
        alert.alertStyle = .informational
        alert.addButton(withTitle: "确定")
        alert.runModal()
    }
}
